<template>
  <div class="app-container">
    <div class="filter-container" id="filter-container-TmptData">

      <el-input
          v-model="listQuery.columnName"
          size="small"
          placeholder="列名"
          style="width: 100px; "
          class="filter-item"
          @keyup.enter.native="handleFilter"
      />

      <select-option
          v-model="listQuery.deleteflag"
          size="small"
          placeholder="删除标志"
          style="width: 100px; "
          class="filter-item"
          :clearable=true
          prop-name="deleteFlag"
          :prop-ds-type=1
      />

      <el-button :loading="queryLoading" class="filter-item" size="small" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button v-show="hasPermission(['tmptData:create'])" class="filter-item" size="small" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button class="filter-item" style="margin-left: 0px;" size="small" type="primary" icon="el-icon-edit"
                 @click="handleBankupsAndRestore()">
        备份还原
      </el-button>
      <!--<el-button v-waves class="filter-item" size="small" type="primary" icon="el-icon-download" @click="handleBackups">
        下载备份
      </el-button>
      <el-upload action="/"
                 ref="upload"
                 accept=".txt"
                 :before-upload="beforeUpload"
                 :disabled="this.fileList.length !== 0"
                 :default-file-list="this.fileList"
      >
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" :disabled="this.fileList.length !== 0">上传备份（*.TXT）</el-button>
      </el-upload>
      <el-button :disabled="this.fileList.length == 0" v-waves class="filter-item" size="small" type="primary" icon="el-icon-download" @click="handleInsertBackups">
        插入备份
      </el-button>-->
    </div>

    <el-table
        :key="tableKey"
        v-loading="listLoading"
        @selection-change="selectionChangeHandle"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
        @row-click="handleRowClick"
        :height="tableHeight"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <!-- 行展开，显示的详细信息 -->
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="ID" >
                  <span>{{ props.row.id }}</span>
                </el-form-item>
                <el-form-item label="columnName" >
                  <span>{{ props.row.columnName }}</span>
                </el-form-item>
                <el-form-item label="description" >
                  <span>{{ props.row.description }}</span>
                </el-form-item>
                <el-form-item label="删除标志" >
                  <span>{{ props.row.deleteflag }}</span>
                </el-form-item>
                <el-form-item label="创建日期" >
                  <span>{{ props.row.createdate }}</span>
                </el-form-item>
                <el-form-item label="创建人" >
                  <span>{{ props.row.createman }}</span>
                </el-form-item>
                <el-form-item label="修改日期" >
                  <span>{{ props.row.modifydate }}</span>
                </el-form-item>
                <el-form-item label="修改人" >
                  <span>{{ props.row.modifyman }}</span>
                </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column label="ID" align="center" width="60px">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="列名" align="center" min-width="100px">
        <template slot-scope="{row}">
              <el-input v-if="row.edit" v-model="row.columnName" class="edit-input" size="mini" />
              <span v-else>{{ row.columnName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="删除标志" align="center">
        <template slot-scope="{row}">
              <select-option
                  v-if="row.edit"
                  v-model="row.deleteflag.id"
                  size="mini"
                  style="width: 70px; "
                  class="edit-input"
                  prop-name="deleteflag"
                  :prop-ds-type=1
              />
              <select-option
                  v-else
                  :disabled=true
                  v-model="row.deleteflag.id"
                  size="mini"
                  style="width: 70px; "
                  class="edit-input"
                  prop-name="deleteflag"
                  :prop-ds-type=1
              />
        </template>
      </el-table-column>

      <!--操作Button + 页面级权限控制:hasPermission -->
      <el-table-column v-if="hasPermission(['tmptData:update','tmptData:delete'])" fixed="right" label="操作" align="center" min-width="240">
        <template slot-scope="{row,$index}">
          <el-button v-show="row.edit" type="success" icon="el-icon-close"  title="取消" size="mini" @click="cancelEdit(row)"></el-button>
          <el-button v-if="row.edit" type="success" icon="el-icon-check"  title="保存" size="mini" @click="confirmEdit(row)"></el-button>
          <el-button v-show="hasPermission(['tmptData:update'])" v-else type="primary" icon="el-icon-edit"  title="编辑" size="mini" @click="row.edit=!row.edit"></el-button>
          <el-button v-show="hasPermission(['tmptData:delete'])" type="danger" icon="el-icon-delete"  title="删除" size="mini" @click="handleDelete(row)"/>
          <el-button size="mini" @click="handleCreateBuildCode4Enums(row)">生成枚举源码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <form-details ref="formDetails" :row="row" :isFromFather="true" @createResult="createResult"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
    <!--BankupsAndRestore-->
    <el-dialog title="备份还原" :visible.sync="dialog4BankupsAndRestoreVisible" width="30%" >
      <TmptBankupRestore ref="tmptBankupRestore" :idListStr="idListStr" :isFromFather="true" @insertFileResult="insertFileResult"/>
    </el-dialog>
<!--    &lt;!&ndash;BankupsAndRestore&ndash;&gt;-->
<!--    <el-dialog :visible.sync="dialog4BankupsAndRestoreVisible" :close-on-click-modal="false" title="备份还原" width="30%">-->
<!--      <TmptBankupRestore ref="tmptBankupRestore" :idListStr="idListStr"/>-->
<!--    </el-dialog>-->

  </div>
</template>

<script>
import {fetchList,
/*  fetchBankupByIds,
  insertBankup,*/
  updateApi, deleteApi, buildCode4EnumsApi} from './api'
import waves from '@/directive/waves' // waves directive
import { parseTime, reorgQueryParams, resizeTableHeight } from '@/utils'
import checkPermission from '@/utils/permission'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import FormDetails from './form-details.vue' // add form form dialog
// 从当前View的私有数据对象中取数据
import { pickerOptions, pickerOptionsSingleDate } from './data'
import TmptBankupRestore from './tmpt-bankup-restore'
// 导入多选项组件
import SelectOption from '@/views/coding/components/SelectOption'

export default {
    name: 'TmptData-ListLineEdit',

    components: { Pagination, FormDetails, TmptBankupRestore, SelectOption },
    directives: { waves },

    props: {
        // 作为子组件时，需要回调传值；应用场景：一对多关联查询时，点击左边查询列表，传值给右边子列表，查询子列表结果
        isFromFather: {
            type: Boolean,
            default: false
        },
        // 当作为侧边查询结果显示的右子组件时，接收父组件的传值，watch中查询
        parentRow: Object
    },

    filters: {
        statusFilter(status) {
            const statusMap = {
                published: 'success',
                draft: 'info',
                deleted: 'danger'
            }
            return statusMap[status]
        }
    },

    data() {
        return {
          tableKey: 0,
          list: null,
          total: 0,
          listLoading: false,
          queryLoading: false,
          downloadLoading: false,
          listQuery: {
              page: 1,
              limit: 20
          },
         //备份表的id
          idListStr: '',
          //上传的file
          /*       fileList:[],
                fileListStr:'',*/
          dialog4BankupsAndRestoreVisible:false,
          importanceOptions: [1, 2, 3],
          sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
          statusOptions: ['published', 'draft', 'deleted'],
          dialogFormVisible: false,
          dialogStatus: '',
          textMap: {
              update: '编辑',
              create: '新增'
          },
          pickerOptions: pickerOptions,
          pickerOptionsSingleDate: pickerOptionsSingleDate,
          deleteflagList: [], // 多选项列表
          row: {},
          tableHeight:0, // 表格高度
          filterContainerHeight: 0, // 查询容器高度
          clientHeight: 0 // 浏览器高度
        }
    },
    watch: {
        // 当作为侧边查询的子组件时，接收父组件的传值，watch中查询
        parentRow(row) {
            this.listQuery.parantId = row.id // parantId, 需修改成主表ID。******
            this.handleFilter()
        }
    },

    created() {
        this.getList()
    },

    mounted () {
        // 浏览器、元素大小变化时，动态调整table高度
        resizeTableHeight(this, 'filter-container-TmptData')
    },
  beforeCreate() {
    // // 读取文件
    // FileReader.prototype.reading = function({ encode } = pms) {
    //   let bytes = new Uint8Array(this.result)    //无符号整型数组
    //   let text = new TextDecoder(encode || 'UTF-8').decode(bytes)
    //   return text
    // }
    // /* 重写readAsBinaryString函数 */
    // FileReader.prototype.readAsBinaryString = function(f) {
    //   if (!this.onload)       //如果this未重写onload函数，则创建一个公共处理方式
    //   {
    //     this.onload = e => {  //在this.onload函数中，完成公共处理
    //       let rs = this.reading()
    //       console.log(rs)
    //
    //     }
    //   }
    //   this.readAsArrayBuffer(f)  //内部会回调this.onload方法
    // }
  },

    methods: {
        // 页面级权限控制，调用方法如：hasPermission(['a2user:delete'])
        hasPermission(needPermisions) {
          return checkPermission(needPermisions)
        },
        // 刷新
        getList() {
            this.queryLoading = true
            this.listLoading = true
            // 重组查询条件
            const params = Object.assign({}, this.listQuery)
            reorgQueryParams(params)
            // 查询
            fetchList(params).then(result => {
                const items = result.map.rows
                this.total = result.map.total
                // 备份数据，编辑还原用
                this.list = items.map(v => {
                    this.$set(v, 'edit', false) // https://vuejs.org/v2/guide/reactivity.html
                    v.original = Object.assign({}, v)
                    return v
                })
                this.queryLoading = false
                this.listLoading = false
            })
        },
        // 从第一页开始查询
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        // 排序
        sortChange(data) {
            const { prop, order } = data
            if (prop === 'id') {
                this.sortByID(order)
            }
        },
        sortByID(order) {
            if (order === 'ascending') {
                this.listQuery.sort = '+id'
            } else {
                this.listQuery.sort = '-id'
            }
            this.handleFilter()
        },
        // 添加操作 start
        handleCreate() {
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            // 消除上次出现的验证信息
            this.$nextTick(() => {
                this.$refs['formDetails'].clearValidate()
                this.$refs['formDetails'].resetTemp()
                this.$refs['formDetails'].defaultTemp()
            })
        },
        handleBankupsAndRestore() {
          this.dialog4BankupsAndRestoreVisible = true
        },
      // handleInsertBackups() {
      //   insertBankup({ 'fileListStr': this.fileListStr }).then(result => {
      //     if (result.success) {
      //       this.getList()
      //       this.$notify({
      //         title: '成功',
      //         message: 'Insert Successfully',
      //         type: 'success',
      //         duration: 2000
      //       })
      //     }
      //   })
      //
      // },
      //
      // handleBackups() {
      //     console.log("11111111111")
      //   fetchBankupByIds({ 'idListStr': this.idListStr }).then(result => {
      //     const items = result.list
      //     console.log("222222222222")
      //     console.log(items)
      //     this.onClickDownDaily('test.txt', items)
      //   })
      //
      // },
      // onClickDownDaily(name, val) {
      //   let s = JSON.stringify(val)
      //   var export_blob = new Blob([s])
      //   var save_link = document.createElement('a')
      //   save_link.href = window.URL.createObjectURL(export_blob)
      //   save_link.download = name
      //   this.fakeClick(save_link)
      // },
      // fakeClick(obj) {
      //   var ev = document.createEvent('MouseEvents')
      //   ev.initMouseEvent(
      //     'click',
      //     true,
      //     false,
      //     window,
      //     0,
      //     0,
      //     0,
      //     0,
      //     0,
      //     false,
      //     false,
      //     false,
      //     false,
      //     0,
      //     null
      //   )
      //   obj.dispatchEvent(ev)
      // },
      // beforeUpload(file) {
      //   this.fileList = [file]
      //   // console.log('选择了文件beforeUpload')
      //   // 读取数据
      //   this.read(file)
      //   return false
      // },
      // read(f) {
      //   let rd = new FileReader()
      //   const _this = this
      //   _this.fileListStr = ''
      //   rd.onload = e => {
      //     //this.readAsArrayBuffer函数内，会回调this.onload函数。在这里处理结果
      //     let cont = rd.reading({ encode: 'utf-8' })
      //     console.log(cont)
      //     _this.fileListStr = cont
      //     // let formerData = this.textData
      //     // this.textData = formerData + '\n' + cont
      //   }
      //   rd.readAsBinaryString(f)
      // },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      // 多选
      selectionChangeHandle(val) {
        const _this = this
        _this.idListStr = ''
        val.forEach(function(value, key, arr) {
          if (_this.idListStr == '') {
            _this.idListStr += value.id
          } else {
            _this.idListStr += ',' + value.id
          }

          console.log(_this.idListStr)

        })
      },
        // download excel
        handleDownload() {
            // 重组查询条件
            const params = Object.assign({}, this.listQuery)
            params.page = 1
            params.limit = 10000000
            reorgQueryParams(params)
            //console.log(params)
            // 查询
            this.downloadLoading = true
            fetchList(params).then(result => {
                import('@/vendor/Export2Excel').then(excel => {
                    const tHeader = ['Id', '名称', '创建时间', '创建人']  // excel中显示的列名
                    const filterVal = ['id', 'name', 'createdate', 'createman'] // excel中显示哪些列，与tHeader对应
                    const list = result.map.rows
                    const data = this.formatJson(filterVal, list)
                    excel.export_json_to_excel({
                        header: tHeader,
                        data,
                        filename: 'excel',
                        autoWidth: true,
                        bookType: 'xlsx'
                    })
                    this.downloadLoading = false
                })
            })
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => {
                if (j === 'timestamp') {
                    return parseTime(v[j])
                } else {
                    return v[j]
                }
            }))
        },
        // 调用子组件操作数据
        createData() {
            this.$refs['formDetails'].createData()
        },
        // 子组件操作成功，回调此方法，关闭弹框、刷新
        createResult() {
            this.dialogFormVisible = false
            this.handleFilter()
        },
        insertFileResult() {
          this.dialog4BankupsAndRestoreVisible = false
          this.handleFilter()
        },
        // 编辑操作 start
        cancelEdit(row) {
            // 还原原始值
            Object.keys(row).forEach(key => {
                if (key !== 'original' && key !== 'edit') {
                    row[key] = row.original[key]
                }
            })
            row.edit = false
            // row.original.edit = false
            this.$message({
                message: '数据恢复到原始值',
                type: 'warning'
            })
        },
        confirmEdit(row) {
            const param = Object.assign({}, row)
            param.original = {}
            updateApi(param).then((r) => {
                this.notify(r)
                if (r.success) {
                    row.edit = false
                    // 原始值：更新成最新输入值
                    Object.keys(row).forEach(key => {
                        if (key !== 'original' && key !== 'edit') {
                            row.original[key] = row[key]
                        }
                    })
                }
            })
        },
        // 删除操作
        handleDelete(row) {
            this.$confirm('确认删除吗？')
                .then(_ => {
                    // delete api
                    deleteApi({ id: '' + row.id }).then((r) => {
                        this.notify(r)
                        if (r.success) {
                            this.getList()
                        }
                    })
                    // end
                })
                .catch(_ => {})
        },
        // 行点击事件；应用场景：一对多关联查询时，点击左边查询列表，传值给右边子列表，查询子列表结果
        handleRowClick(row, column, event) {
            // 从父组件调用此方法，进行回调下
            if (this.isFromFather) {
                this.$emit('input', row)
            }
        },
        // enums源码生成器
        handleCreateBuildCode4Enums(row) {
            this.$confirm('重新生成的-枚举源码-，将覆盖原有源码，请备份好，再执行？')
                .then(() => {
                    const params = {id: row.id}
                    buildCode4EnumsApi(params).then(result => {
                        if(result.success) {
                            this.$notify({
                                title: '结果',
                                message: result.content,
                                type: 'success',
                                duration: 2000
                            })
                        }
                    })
                })
                .catch(_ => {})
        },
        getSortClass: function(key) {
            const sort = this.listQuery.sort
            return sort === `+{key}` ? 'ascending' : 'descending'
        }
    }
}
</script>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
